package com.qf.leadnewsarticle.listener;

import com.qf.leadnewsarticle.feign.WeMediaFeignApi;
import com.qf.leadnewsarticle.service.ApArticleService;
import com.qf.leadnewsmodel.consts.KafkaConst;
import com.qf.leadnewsmodel.pojos.wemedia.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PublishWmNewsListener {

    @Autowired
    private WeMediaFeignApi weMediaFeignApi;

    @Autowired
    private ApArticleService apArticleService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @KafkaListener(topics = KafkaConst.PUBLISH_WMNEWS_TOPIC)
    public void publishNews(String newId, Acknowledgment acknowledgment){

        log.info("=====kafka消费到消息，newsId:{}====",newId);

        WmNews wmNews = weMediaFeignApi.findNewsById(Integer.parseInt(newId));
        if (wmNews != null){
            try {
                //这个是一个事务方法，事务失败，一定会有异常
                /*
                    存在事务成功，但是手动上报点位出现问题，导致这条消息重复消费
                    最终导致Ariticle表中存在两条重复的文章信息
                    --- 幂等性保障
                 */
                Boolean handle = redisTemplate.opsForValue().setIfAbsent(newId, "1", 10, TimeUnit.MINUTES);
                if(handle) {
                    apArticleService.saveArticle(wmNews);
                }

                //事务成功，确认消费消息
                acknowledgment.acknowledge();
            }catch (Exception e){
                //异常后，删除redis中的幂等键，保障重新消费时，可以继续执行业务
                redisTemplate.delete(newId);
                //消息不消费，下次会重新消费 (考虑死循环业务)
                acknowledgment.nack(0);
            }
        }else{
            acknowledgment.acknowledge();
        }
    }
}
